<template>
    <div class="lists">
        <el-card shadow="never" class="!border-none">
            <el-form :model="formData" inline>
                <el-form-item label="服务名称">
                    <el-input
                        class="ls-input"
                        v-model="formData.name"
                        placeholder="请输入服务名称"
                    />
                </el-form-item>
                <el-form-item label="服务分类">
                    <el-cascader
                        v-perms="['category:commonList']"
                        ref="cascaderRef"
                        class="ls-input"
                        v-model="formData.categoryId"
                        :options="categoryData"
                        :props="{
                            checkStrictly: true,
                            label: 'name',
                            value: 'id',
                            children: 'sons',
                            emitPath: false
                        }"
                        clearable
                        filterable
                        @change="handleChange"
                    />
                </el-form-item>
                <el-form-item>
                    <div class="m-l-20">
                        <el-button type="primary" @click="resetPage">查询</el-button>
                        <el-button @click="resetParams">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="never" class="mt-4 !border-none">
            <el-tabs
                class="-mt-2"
                v-model="formData.status"
                @tab-change="resetPage"
                v-perms="['goods:statistics']"
            >
                <el-tab-pane :label="`全部(${countData?.allCount || '0'})`" name="" />
                <el-tab-pane :label="`销售中(${countData?.inSalesCount || '0'})`" :name="1" />
                <el-tab-pane :label="`仓库中(${countData?.warehouseCount || '0'})`" :name="0" />
            </el-tabs>

            <div class="mt-2">
                <el-button
                    type="primary"
                    @click="$router.push('lists/edit')"
                    v-perms="['goods:add']"
                    >添加服务</el-button
                >
                <el-button
                    v-perms="['goods:status']"
                    @click="handleChangeStatus(selectionData, 0)"
                    :disabled="!selectionData.length"
                >
                    批量上架
                </el-button>
                <el-button
                    v-perms="['goods:status']"
                    @click="handleChangeStatus(selectionData, 1)"
                    :disabled="!selectionData.length"
                >
                    批量下架
                </el-button>
                <el-button
                    v-perms="['goods:del']"
                    @click="handleDelete(selectionData)"
                    :disabled="!selectionData.length"
                >
                    批量删除
                </el-button>
            </div>

            <div class="mt-4">
                <el-table
                    ref="tableData"
                    :data="pager.lists"
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                    v-loading="pager.loading"
                >
                    <el-table-column type="selection" max-width="55" />
                    <el-table-column property="name" label="服务名称" min-width="260">
                        <template #default="scope">
                            <div class="flex items-center">
                                <div class="w-[60px] h-[60px]">
                                    <el-image
                                        style="width: 60px; height: 60px"
                                        :src="scope.row.image"
                                        :preview-src-list="[scope.row.image]"
                                        :hide-on-click-modal="true"
                                        :preview-teleported="true"
                                        :fit="'contain'"
                                    />
                                </div>
                                <el-tooltip :content="scope.row.name" placement="top">
                                    <div class="ml-2 truncate">{{ scope.row.name }}</div>
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column property="category" label="服务分类" min-width="145" />
                    <el-table-column property="price" label="价格" min-width="120">
                        <template #default="scope"> ¥{{ scope.row.price }} </template>
                    </el-table-column>
                    <el-table-column property="unit" label="单位" min-width="120" />
                    <el-table-column property="orderNum" label="预约人数" min-width="120" />
                    <el-table-column property="statusDesc" label="销售状态" min-width="100">
                        <template #default="scope">
                            <el-tag type="success" v-if="scope.row.status == 1">销售中</el-tag>
                            <el-tag type="info" v-if="scope.row.status == 0">仓库中</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column property="sort" label="排序" min-width="90" />
                    <el-table-column property="createTime" label="添加时间" min-width="180" />
                    <el-table-column property="address" label="操作" width="180" fixed="right">
                        <template #default="scope">
                            <div class="flex items-center">
                                <router-link
                                    v-perms="['goods:edit', 'goods:detail']"
                                    class="mr-4"
                                    :to="{
                                        path: 'lists/edit',
                                        query: {
                                            id: scope.row.id
                                        }
                                    }"
                                >
                                    <el-link type="primary" :underline="false">编辑</el-link>
                                </router-link>

                                <div class="mr-4">
                                    <el-link
                                        v-perms="['goods:status']"
                                        type="primary"
                                        :underline="false"
                                        @click="handleChangeStatus(scope.row.id, scope.row.status)"
                                    >
                                        {{ !scope.row.status ? '立即上架' : '放入仓库' }}
                                    </el-link>
                                </div>

                                <el-link
                                    v-perms="['goods:delete']"
                                    type="danger"
                                    :underline="false"
                                    @click="handleDelete(scope.row.id)"
                                    >删除</el-link
                                >
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists"></pagination>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import {
    apiServiceLists,
    apiServiceDel,
    apiServiceStatus,
    apiServiceStatis
} from '@/api/service/lists'
import { apiCategoryCommonLists } from '@/api/service/category'
import { ref } from 'vue'
import Pagination from '@/components/pagination/index.vue'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'

interface formDataObj {
    name: string //服务名称
    status?: number | string //服务状态:1-销售中;0-仓库中
    categoryId: string
}

// 表单数据
const formData = ref<formDataObj>({
    name: '',
    status: '',
    categoryId: ''
})

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: apiServiceLists,
    params: formData.value
})

// 选中的服务项目
const selectionData = ref<number[]>([])

// 服务分类下拉数据
const categoryData = ref([])
const cascaderRef = ref()

// 表格多选选择的数据
const handleSelectionChange = (val: Event | any) => {
    selectionData.value = val.map((item: Event | any) => item.id)
}

// 服务状态 存放仓库 || 立即上架
const handleChangeStatus = async (ids: number | Array<number>, status: number) => {
    status = status === 0 ? 1 : 0
    ids = Array.isArray(ids) ? ids : [ids]
    if (status === 0) {
        await feedback.confirm('确认放入仓库？请谨慎操作。')
    } else if (status === 1) {
        await feedback.confirm('确认上架？请谨慎操作。')
    }
    await apiServiceStatus({ ids, status })
    feedback.msgSuccess('操作成功')
    getLists()
    getOrderAmount()
}

// 删除服务
const handleDelete = async (ids: number | Array<number>) => {
    ids = Array.isArray(ids) ? ids : [ids]
    await feedback.confirm(
        '如果该服务已被师傅关联，此次操作也会同时删除师傅关联的服务项目，请谨慎操作。'
    )
    await apiServiceDel({ ids })
    feedback.msgSuccess('操作成功')
    getLists()
    getOrderAmount()
}

// 获取分类通用列表
const getCategoryLists = async (): Promise<void> => {
    const res = await apiCategoryCommonLists()
    categoryData.value = res
}

// 记录级联选择器所选中的最后一个元素的id
const handleChange = () => {
    const node = cascaderRef.value.getCheckedNodes()
    console.log('id:', node[0])

    formData.value.categoryId = node[0]?.data.id
}

const countData = ref<any>({})
const getOrderAmount = async () => {
    countData.value = await apiServiceStatis('')
}

getOrderAmount()
getLists()
getCategoryLists()
</script>

<style lang="scss" scoped>
.lists {
    .el-radio-button__inner {
        padding: 8.5px 40px;
    }
}
.ls-input {
    width: 280px;
}

.el-tabs__nav-wrap::after {
    height: 1px !important;
}
:deep() .el-tabs__content {
    padding: 0;
}
</style>
